<template>
  <!-- 最新融资法 -->
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('融资日期')" prop="financingDate">
            <el-date-picker
              v-model="form.financingDate"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('融资日期')"
              @change="$forceUpdate()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资轮次')" prop="financingRounds">
            <el-input v-model="form.financingRounds" :placeholder="$t('融资轮次')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资总金额') + $t('金额单位')" prop="totalFinancingAmount">
            <Money v-model="form.totalFinancingAmount" :unit="'w'" disabled :placeholder="$t('总投资成本')" />
          </el-form-item>
        </el-col>
        <!-- 融资方式 -->
        <el-col :span="12">
          <el-form-item :label="$t('融资方式')" prop="financingMethods">
            <dictSelect
              v-model="form.financingMethods"
              :clearable="true"
              dictionary="financing_mode"
            />
          </el-form-item>
        </el-col>
        <!-- 融资前公司估值 -->
        <el-col :span="12">
          <el-form-item :label="$t('融资前公司估值') + $t('金额单位')" prop="preValuation">
            <Money v-model="form.preValuation" :unit="'w'" :placeholder="$t('融资前公司估值')" />
          </el-form-item>
        </el-col>
        <!-- 融资后公司估值 -->
        <el-col :span="12">
          <el-form-item :label="$t('融资后公司估值') + $t('金额单位')" prop="afterValuation">
            <Money v-model="form.afterValuation" :unit="'w'" :placeholder="$t('融资后公司估值')" @change="calculation" />
          </el-form-item>
        </el-col>
        <!-- 融资后每股价格 -->
        <el-col :span="12">
          <el-form-item :label="$t('融资后每股价格') + $t('(元)')" prop="pricePerShare">
            <el-input v-model="form.pricePerShare" :placeholder="$t('融资后每股价格')">
              <template slot="append" icon="el-icon-search">
                <el-checkbox v-model="form.automaticPriceCalculation" :true-label="'true'" :false-label="'false'">{{ $t('自动计算') }}</el-checkbox>
                <el-tooltip :content="$t('选中后自动计算股价或手动录入指定股价, 自动计算: 所有股东的投资金额/变更股数')">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <!-- 我方最新持股比例 -->
        <el-col :span="12">
          <el-form-item :label="$t('我方最新持股比例') + '(%)'" prop="shareholdingRatio">
            <Money v-model="form.shareholdingRatio" disabled :placeholder="$t('我方最新持股比例')" />
          </el-form-item>
        </el-col>
        <!-- 项目估值 -->
        <el-col :span="12">
          <el-form-item :label="$t('项目估值') + $t('金额单位')" prop="dealValuation">
            <Money v-model="form.dealValuation" :unit="'w'" disabled :placeholder="$t('项目估值')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('备注')" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 投资人信息 -->
      <div class="area-header" style="margin-top: 10px;">
        <span class="area-header-title">{{ $t('投资人信息') }}</span>
      </div>
      <el-table tooltip-effect="darkTable" :data="form.investorList" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="80">
          <template slot-scope="scope">
            <span :style="{ color: (isEmpty(scope.row.shareholderId)) ? 'black' : 'red'}">{{ (scope.$index + 1) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('投资人名称')" align="center" width="220">
          <!--<template slot-scope="scope">-->
          <!--  <el-form-item :prop="'investorList.' + scope.$index + '.shareholderName'">-->
          <!--    <span>{{ scope.row.shareholderName }}</span>-->
          <!--  </el-form-item>-->
          <!--</template>-->
          <template slot-scope="scope">
            <el-form-item :prop="'investorList.' + scope.$index + '.shareholderName'" :rules="investorListRules.shareholderName">
              <el-autocomplete
                id="shareholderName"
                v-model="scope.row.shareholderName"
                popper-class="my-autocomplete"
                :fetch-suggestions="querySearch"
                :placeholder="$t('请输入')"
                @select="handleSelect($event, scope.row)"
                @change="choiceHoldShare($event, scope.$index)"
              >
                <i
                  slot="suffix"
                  class="el-icon-edit el-input__icon"
                />
                <template slot-scope="{ item }">
                  <div>{{ item.investorName }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('本轮投资金额') + $t('金额单位')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('本轮投资金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'investorList.' + scope.$index + '.investAmount'" :rules="investorListRules.investAmount">
              <Money v-model="scope.row.investAmount" :unit="'w'" :placeholder="$t('本轮投资金额')" @change="calculation" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('变更股数') + $t('(万股)')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('变更股数') }}{{ $t('(万股)') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'investorList.' + scope.$index + '.resultShare'" :rules="investorListRules.resultShare">
              <Money v-model="scope.row.resultShare" :unit="'w'" :placeholder="$t('变更股数')" @change="calculation" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('每股价格') + $t('(元)')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('每股价格') }}{{ $t('(元)') }}</span>
            <el-tooltip :content="$t('本轮投资金额 / 变更股数')">
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'investorList.' + scope.$index + '.pricePerShare'" :rules="investorListRules.pricePerShare">
              <Money v-model="scope.row.pricePerShare" disabled :placeholder="$t('每股价格')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="140">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="delInvestor(scope.$index, scope.row)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-dropdown trigger="click" placement="top-end">
          <el-button type="primary" size="mini" @click="addInvestor">{{ $t('添加') }}</el-button>
        </el-dropdown>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: left;left: 0;">
      <el-button v-if="!isEmpty(form.capTableTime)" @click="setFormByCapTable()">{{ $t('填入CapTable数据') }}({{ parseTime(form.capTableTime) }})</el-button>
      <el-button v-if="!isEmpty(form.lastFinancingTime)" @click="setFormByFinancing()">{{ $t('填入上次估值填写数据') }}({{ parseTime(form.lastFinancingTime) }})</el-button>
    </div>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <el-button type="warning" @click="calculation">{{ $t('计算') }}</el-button>
      <el-button @click="cancel">{{ $t('取消') }}</el-button>
      <el-button :type="'primary'" @click="submitForm">{{ $t('保存') }}</el-button>
    </div>
  </div>
</template>

<script>
import {
  getValuationMethodFinancingInfo
} from '@/api/deal/analysisValuation/dealAnalysisValuation'
import { ruoyiFloat } from '@/utils/ruoyi'
import { listDealInvestment } from '@/api/deal/investment/dealInvestment'

export default {
  components: {},
  props: {},
  data() {
    return {
      // 遮盖层
      loading: false,
      form: {
        automaticPriceCalculation: 'true'
      },
      rules: {
        financingDate: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }],
        financingRounds: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }],
        totalFinancingAmount: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }],
        financingMethods: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }],
        shareholdingRatio: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }],
        dealValuation: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }],
        preValuation: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }],
        afterValuation: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }],
        pricePerShare: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }]
      },
      investorListRules: {
        shareholderName: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }],
        investAmount: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }],
        resultShare: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }],
        pricePerShare: [{ required: true, message: this.$t('必填信息'),	trigger: ['change', 'blur'] }]
      },
      restaurants: [],
      financingMethodsOption: [],
      capTableData: {},
      lastFinancingData: {},
      capTableTime: undefined,
      lastFinancingTime: undefined,
      dealId: undefined
    }
  },
  watch: {},
  created() {
  },
  methods: {
    init(data) {
      this.loading = true
      this.dealId = data.dealId
      getValuationMethodFinancingInfo(data.dealId).then(response => {
        this.form = response.data
        this.initData(this.form)
        this.$refs.form.resetFields()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    initData(data) {
      // 加载投资主体数据
      this.loadInvestmentData()
      // capTable
      this.capTableData = this.isEmpty(data.capTableData) ? {} : JSON.parse(JSON.stringify(data.capTableData))
      this.capTableData.shareholdingRatio = data.shareholdingRatio
      this.capTableData.capTableTime = data.capTableTime
      this.capTableData.lastFinancingTime = data.lastFinancingTime

      // lastFinancingData
      this.lastFinancingData = this.isEmpty(data.lastFinancingData) ? {} : JSON.parse(JSON.stringify(data.lastFinancingData))
      this.lastFinancingData.shareholdingRatio = data.shareholdingRatio
      this.lastFinancingData.capTableTime = data.capTableTime
      this.lastFinancingData.lastFinancingTime = data.lastFinancingTime
    },
    edit(data) {
      console.log('edit', data)
      this.form = data
      this.dealId = this.form.dealId
      this.loading = true
      getValuationMethodFinancingInfo(this.dealId).then(response => {
        this.form.capTableTime = response.data.capTableTime
        this.form.lastFinancingTime = response.data.lastFinancingTime
        this.initData(response.data)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 选择投资主体触发方法 **/
    querySearch(queryString, cb) {
      const restaurants = this.restaurants
      const results = queryString ? restaurants.filter(obj => ((this.isEmpty(obj.investorName) ? '' : obj.investorName).includes(queryString))) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    /** 选择投资主体数据 **/
    handleSelect(item, row) {
      // 遍历判断是否存在这个投资主体
      var flag = false
      this.form.investorList && this.form.investorList.forEach(detail => {
        if (detail.shareholderId === item.id) {
          flag = true
        }
      })
      if (flag) {
        this.msgError(this.$t('不能重复选择投资主体，请重新选择或者输入！'))
        row.shareholderId = ''
      } else {
        row.shareholderId = item.id
        row.shareholderName = item.investorName
        if (!this.editExistShareStatus) {
          row.existShare = this.formatNum(item.numberOfShares)
        }
      }
    },
    /** 股东名称改变时校验是否是投资主体 **/
    choiceHoldShare(queryString, index) {
      const restaurants = this.restaurants
      const results = queryString ? restaurants.filter(obj => ((this.isEmpty(obj.investorName) ? '' : obj.investorName).includes(queryString))) : restaurants
      if (results === undefined || results === null || results === '' || results.length <= 0) {
        this.form.detailList[index].shareholderId = ''
      }
    },
    /** 加载投资主体数据 **/
    loadInvestmentData() {
      listDealInvestment({ dealId: this.dealId }).then(response => {
        this.restaurants = response.rows
      })
    },
    /** 添加投资人 **/
    addInvestor() {
      const row = {
        shareholderId: undefined,
        shareholderName: undefined,
        investAmount: undefined,
        resultShare: undefined,
        pricePerShare: undefined
      }
      if (!(this.form.investorList instanceof Array)) {
        this.$set(this.form, 'investorList', [])
      }
      this.$nextTick(() => {
        this.form.investorList.push(row)
      })
    },
    /** 删除投资人 **/
    delInvestor(index) {
      this.form.investorList.splice(index, 1)
      this.calculation()
    },
    /** 设置capTable **/
    setFormByCapTable() {
      this.form = this.capTableData
      this.$set(this.form, 'financingDate', this.parseTime(this.capTableData.financingDate))
      this.calculation()
      this.$forceUpdate()
    },
    /** 设置上次融资 **/
    setFormByFinancing() {
      this.form = this.lastFinancingData
      this.$set(this.form, 'financingDate', this.parseTime(this.lastFinancingData.financingDate))
      this.calculation()
      this.$forceUpdate()
    },
    /** 自动计算 **/
    calculation() {
      var money = 0
      this.form.investorList && this.form.investorList.forEach((item) => {
        if (!this.isEmpty(item.investAmount)) {
          money += item.investAmount
        }
      })
      this.form.totalFinancingAmount = money
      // 项目估值 dealValuation 融资后公司估值 (万) × 我方最新持股比例(%)
      this.form.dealValuation = this.formatNum(this.form.afterValuation) * (this.formatNum(this.form.shareholdingRatio) / 100)
      var shareholderMoney = 0
      var shareholderNumber = 0
      this.form.investorList && this.form.investorList.forEach((item, index) => {
        shareholderMoney += this.formatNum(item.investAmount)
        shareholderNumber += this.formatNum(item.resultShare)
        // 每股价格(元) = 本轮投资金额(万) / 变更股数(万股) 最多保留6位小数
        if (this.formatNum(item.resultShare) === 0) {
          this.$set(this.form.investorList[index], 'pricePerShare', 0)
        } else {
          this.$set(this.form.investorList[index], 'pricePerShare', (this.formatNum(item.investAmount) / this.formatNum(item.resultShare)).toFixed(6))
        }
      })
      // 融资后每股价格 = 所有股东的投资金额/变更股数
      if (this.form.automaticPriceCalculation === 'true') {
        if (this.formatNum(shareholderNumber) === 0) {
          this.$set(this.form, 'pricePerShare', 0)
        } else {
          this.$set(this.form, 'pricePerShare', (this.formatNum(shareholderMoney) / this.formatNum(shareholderNumber)).toFixed(6))
        }
      }
    },
    /** 格式化金额, 保留精度及小数 **/
    formatNum(num) {
      if (num === null || num === undefined || isNaN(num)) {
        num = 0
      }
      return ruoyiFloat().formatNum(Number(num).toFixed(4))
    },
    /** 取消 **/
    cancel() {
      this.$parent.$parent.methodFinancingLawOpen = false
    },
    /** 提交 **/
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$emit('financingLawAddMethod', this.form)
          this.cancel()
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
